<?php

/** 
 * 后台_充值_控制器
 * @property Recharge_order_mdl $rechargeOrder
 * @property User_mdl $users
 * @property WxPayApi $wxPayApi
 * @property ApiOutput $apiOutput
 */
class Recharge extends Admin_Controller {
	private $defaultPayTimeStart = 0;
	private $defaultQuery = array();
	private $defaultWhere = array();
	public function __construct() {
		parent::__construct ();
		$this->load->model('Recharge_order_mdl','rechargeOrder');
		$this->load->model('School_mdl','school');
		$this->defaultPayTimeStart = time() - 86400 * 7;
		
	}
	
	public function order(){
		$this->load->library('Search_tpl',NULL,'searchTpl');
		$where = array();
		$like  = array();
		$order = 'id';
		$sort  = 'DESC';
		$orders = array(
				'orderID'=>'id',
				'uid'=>'userID',
				'time'=>'time',
		);
		$input = $this->input->get(NULL,TRUE);
		foreach ($input as $k=>$v){
			if ($v===''){
				continue;
			}
			$v = trim($v);
			switch ($k) {
				case 'orderID':
					$where['id'] = (int)$v;
					break;
				case 'uid':
					$where['userID'] = (int)$v;
					break;
				case 'nickname':
					$like['nickname'] = $v;
					break;
				case 'tradeState':
					if( $v!='ALL' ){
						$where['tradeState'] = $v;
					}
					break;
				case 'rc_st':
					$where['payTime >='] = strtotime($v);
					break;
				case 'rc_et':
					$where['payTime <='] = strtotime($v);
					break;
				case 'order' :
					$order = isset($orders[$v]) ? $orders[$v] : 'id';
					break;
				case 'sort':
					$sort = (int)$v===0 ? 'DESC' : 'ASC';
					break;
				case 'phone':
					$where['phone'] = (float)$v;
					break;
			}
		}
		$query = array();
		$query['select']= '*';
		$query['from']  = MY_Model::T_RECHARGE_ORDER;
		$query['join']  = array(
				'table'=>MY_Model::T_USER,
				'select'=>'nickname',
				'on'=>array('fk'=>'userID','pk'=>'id'),
				'type'=>'left',
		);
		$query['where'] = $where;
		$query['like']  = $like;
		$query['order'] = $order;
		$query['sort']  = $sort;
		$list = $this->searchTpl->query($query);
		$temp = array();
		$temp['formItems'] = array(
				'orderID',
				'uid',
				'nickname',
				'tradeState',
				'br',
				'school',
				array('label'=>'充值时间','type'=>'dateRange','name'=>array('rc_st','rc_et')),
		);
		$temp ['thList'] = array (
				array('text'=>'订单ID','order'=>'id'),
				array('text'=>'用户ID','order'=>'uid'),
				'用户昵称',
				'充值金额',
				'订单状态',
				'商户订单号',
				'微信订单号',
				'充值时间',
				'操作',
		);
		$callback = function($v){
			return array(
					$v['id'],
					$v['userID'],
					$v['nickname'],
					($v['amount']/100).'元',
					$this->rechargeOrder->tradeStateCN[$v['tradeState']],
					$v['tradeID'],
					$v['wxTransactionID'],
					date('Y-m-d H:i:s',$v['payTime']),
					'',
// 					'<button type="button" class="ibtn" onclick="queryWxOrderState(this,'.$v['id'].')">查询</button>',
			);
		};
		$temp['tradeStateCnList'] = $this->rechargeOrder->tradeStateCN;
		$temp['tableTitle'] = '订单列表--共查到%s张订单--';
		$temp['jsCtrl'] = 'rechargeOrderCtrl';
		$temp['header'] = $this->getViewHeaderData();
// 		$temp['schoolList'] = $this->school->getSchoolList();
		$this->searchTpl->show($temp,$callback);
		
	}
	
	public function wx_order_query(){
		$orderID = (int)$this->input->post_get('id',TRUE);
		if( empty($orderID) ){
			$this->apiOutput->errorInput();
		}
		$order = $this->rechargeOrder->queryOrderResult($orderID);
		$this->apiOutput->put('tradeState',$order['tradeState'])
					->put('msg',$order['tradeStateDesc'])
					->put('amount',(int)$order['amount'])
					->out();
		
	}
	
	public function stat(){
		
		$this->defaultWhere['tradeState'] = 'SUCCESS';
		$this->defaultWhere['wxTradeType !='] = 'CARD';
		
		$user=$_SESSION['admin'];
		if( empty($user) ){
			alert('未登录！',ADMIN_DIR.'login/login');
		}
		$school_id=isset($user['school_id'])?$user['school_id']:0;
		
		if($school_id!=0){
			$school_id_arr=explode(',',$school_id);
			$school_id=intval($school_id_arr[0]);
		}
		if(isset($_REQUEST['schoolID'])&&$_REQUEST['schoolID']>0){
			$school_id=$_REQUEST['schoolID'];
		}
		if( !empty($_REQUEST['downExcel']) ){
			$this->downExcel();
			return TRUE;
		}
		
		// 输出HTML
		if( empty($_REQUEST['type']) ){
			$this->statHTML();
			return TRUE;
		}
		
		// 获取列表
		$type = $_REQUEST['type'];
		$_REQUEST['tradeState'] = 'SUCCESS';
		if( $type == 'chart' ){
			$this->chartData($school_id);
		}else if( $type == 'list' ){
			$this->listData($school_id);
		}
	}
	
	private function downExcel(){
		$this->apiOutput->debug = TRUE;
		$rest = $this->search (  TRUE );
		$list = $rest['list'];
		
// 		unset($rest['list']);
// 		$rest['listCount'] = count($list);
// 		$this->apiOutput->out ( $rest );

		$headers = array(
				'订单ID',
				'支付时间',
				'订单状态',
				'用户ID',
				'用户昵称',
				'学校ID',
				'学校名称',
				'商户订单号',
				'微信支付订单号',
		);
		$schoolList = $schoolList = $this->school->getSchoolList();
		$list = array_map(function($row)use($schoolList){
			return array(
					$row['id'],
					date('Y-m-d H:i:s',$row['payTime']),
					$row['tradeState'],
					$row['userID'],
					$row['nickname'],
					$row['schoolID'],
					empty($schoolList[$row['schoolID']]) ? '' : $schoolList[$row['schoolID']]['name'],
					$row['tradeID'],
					$row['wxTransactionID']
			);
		}, $list);
		
		array_unshift($list, $headers);
		
		$filename = '充值记录.csv';
		header ( 'Content-Type: application/vnd.ms-excel' );
		header ( 'Content-Disposition: attachment;filename=' . $filename );
		header ( 'Cache-Control: max-age=0' );
		$fp = fopen ( 'php://output', 'a' );
		$limit = 1000;
		foreach ($list as $index=>$row){
			$row = array_map('utf8ToGbk', $row);
			fputcsv($fp, $row);
		}
		fclose($fp);
		
	}
	
	private function statHTML(){
		$formItems = array(
				array('type'=>'text','name'=>'uid','label'=>'用户ID'),
				array('type'=>'text','name'=>'nickname','label'=>'用户昵称'),
				'school',
				'br',
				array(
						'type' => 'dateRange',
						'label' => '充值时间',
						'begin' => array('name'=>'rc_st','value'=>date('Y-m-d 00:00:00',$this->defaultPayTimeStart)),
						'end'   => array('name'=>'rc_et','value'=>date('Y-m-d 23:59:59')),
				),
		);
		$statTemp = array(
				'config'=>array(
						'api'=>base_url( ADMIN_DIR.'recharge/stat'),
						'thItems'=>array(
								array('text'=>'订单ID','order'=>'id'),
								array('text'=>'用户ID','order'=>'uid'),
								'用户昵称',
								'学校',
								'充值金额',
								array('text'=>'充值时间','order'=>'time'),
						),
						'tdClass'=>array(
								1=>'userID',
								2=>'username',
								4=>'amount',
						),
				),
		);
		$this->showHeader();
		$this->showSearchForm($formItems,array('downExcel'=>1));
		$this->showStat($statTemp);
		$this->showFooter();
	}
	
	private function condition(){
		$input = array_merge($this->defaultQuery,$_REQUEST);
		$where   = array(
// 				'payTime >='=>$this->defaultPayTimeStart
		);
		$where = array_merge($this->defaultWhere,$where);
		$like    = array();
		$order   = 'id';
		$sort    = 'DESC';
		$page    = 1;
		$pagesize = 20;
		$orders = array(
				'orderID'=>'id',
				'uid'=>'userID',
				'time'=>'id',
		);
		foreach ($input as $k=>$v){
			$v = trim($v);
			if ($v===''){
				continue;
			}
			
			switch ($k) {
				case 'schoolID':
					$v = (int)$v;
					if($v > 0){
						$where['schoolID'] = $v;
					}
					break;
				case 'orderID':
					$where['id'] = (int)$v;
					break;
				case 'uid':
					$where['userID'] = (int)$v;
					break;
				case 'nickname':
					$like['nickname'] = $v;
					break;
				case 'tradeState':
					if( $v!='ALL' ){
						$where['tradeState'] = $v;
					}
					break;
				case 'order' :
					$order = isset($orders[$v]) ? $orders[$v] : 'id';
					break;
				case 'sort':
					$sort = (int)$v===0 ? 'DESC' : 'ASC';
					break;
				case 'phone':
					$where['phone'] = (float)$v;
					break;
				case 'rc_st':
					$where['payTime >='] = strtotime($v);
					break;
				case 'rc_et':
					$where['payTime <='] = strtotime($v);
					break;
				case 'page' : 
					$v = (int)$v;
					$page = $v > 0 ? $v : 1;
					break;
				case 'pagesize' : 
					$v = (int)$v;
					$pagesize = $v > 0 ? $v : 20;
					break;
				case 'tradetype':
					$where['wxTradeType'] = $v;
					break;
			}
		}
		return array(
				'where'=>$where,
				'like'=>$like,
				'order'=>$order,
				'sort'=>$sort,
				'limit'=>$pagesize,
				'offset'=>($page-1)*$pagesize,
		);
	}
	
	private function search($getAll=FALSE,$schoolID=0){
		$query = $this->condition();
		debug('query',$query);
		$isFirst = $query['offset']===0 ;
		$select = 'o.id,o.userID,o.amount,o.payTime,u.nickname,u.schoolID,o.tradeID,o.tradeState,o.wxTransactionID';
		if( $isFirst ){
			$select = 'SQL_CALC_FOUND_ROWS '.$select;
		}
		if( !$getAll ){
			$this->db->limit($query['limit'],$query['offset']);
		}
		if($schoolID>0){ 
			$query['where']['schoolID']=(int)$schoolID;
		}
		
		$list = $this->db->select($select,FALSE)->from(MY_Model::T_RECHARGE_ORDER.' as o ')
					->join(MY_Model::T_USER.' as u','u.id=o.userID','left')
					->where($query['where'])
					->like($query['like'])
					->order_by($query['order'],$query['sort'])
					->get()
					->result_array();
		$total = null;
		if( $isFirst ){
			$total = (int) $this->db->query('SELECT FOUND_ROWS() AS total ')->row()->total;
		}
		return array(
				'list'=>$list,
				'isFirst' => $isFirst,
				'total'=>$total,
		);
	}
	
	
	private function listData($schoolID=0){
		$query = array('tradeState'=>'SUCCESS','wxTransactionID !='=>0,);
		$res     = $this->search(false,$schoolID);
		$list    = $res['list'];
		$schoolList = array();
		if( ! empty($list) ){
			$schoolList = $this->school->getSchoolList();
		}
		$list = array_map(function($v)use($schoolList){
			return array(
					$v['id'],
					$v['userID'],
					$v['nickname'],
					empty($schoolList[$v['schoolID']]) ? '' : $schoolList[$v['schoolID']]['name'],
					$v['amount']/100,
					date('Y-m-d H:i:s',$v['payTime']),
			);
		}, $list);
		if( $res['isFirst'] ){
			$this->apiOutput->put('total',$res['total']);
		}
		
		$this->apiOutput->put('list', $list)->out();
	}
	
	/**
	 * 图表处理
	 */
	private function chartData($schoolID=0){
		$input = &$_REQUEST;
		
		if( isset($input['rc_st']) ){
			$beginTime = strtotime($input['rc_st']);
		}else{
			$beginTime = strtotime( date( 'Y-m-d',time()-86400*7 ).' 00:00:00' );
		}
		if( isset($input['rc_et']) ){
			$endTime = strtotime($input['rc_et']);
		}else{
			$endTime = time();
		}
		unset($input['rc_st']);
		unset($input['rc_et']);
		unset($input['order']);
		unset($input['sort']);
		unset($input['page']);
		unset($input['pagesize']);
		$query = $this->condition($input);
		
		if($schoolID>0){
			$query['where']['schoolID']=(int)$schoolID;
		}
		if( ! empty($query['where']['schoolID']) || !empty($query['where']['nickname']) ){
			$this->db->join(MY_Model::T_USER.' as u','u.id=o.userID','left');
		}
		$_list = $this->db->select('payTime,amount')
						->from(MY_Model::T_RECHARGE_ORDER.' as o')
						->where('tradeState','SUCCESS')
						->where($query['where'])
						->where('payTime >=',$beginTime)
						->where('payTime <=',$endTime)
						->like($query['like'])
						->get()
						->result_array();
		$list = array();
		$totalAmount = 0;
		foreach ($_list as $v){
			$date = date('Y-m-d',$v['payTime']);
			if( ! isset($list[$date]) ){
				$list[$date] = 0;
			}
			$list[$date] += $v['amount']/100;
			$totalAmount += $v['amount'];
		}
		$amountList = array();
		$dateList   = array();
		for ( $t = $beginTime ; $t <= $endTime ;$t+=86400 ){
			$date = date('Y-m-d',$t);
			$dateList[] = $date;
			$amountList[] = isset($list[$date]) ? round($list[$date],2) : 0 ;
		}
		// 图表配置数组
		$chart = array(
				'xAxis'=>array( // 横坐标
						'data'=>$dateList,
						'type'=>'category',
						'name'=>'日期',
						'boundaryGap'=> false,
				),
				'yAxis'=> array(
						'type'=>'value',
				),
				'legend'=>array(
						'data'=>array('充值金额'),
				),
				'series'=>array(
						array(
								'name'=>'充值金额',
								'type'=>'line',
								'data'=>$amountList,
						),

				),
		);
		$stat = array(
				array('th'=>'消费时间','td'=>date('Y-m-d H:i:s',$beginTime).'至'.date('Y-m-d H:i:s',$endTime)),
				array('th'=>'总充值金额','td'=>($totalAmount/100).'元'),
		);
		$this->apiOutput->put('chart', $chart)->put('stat', $stat)->out();
	}
	
	
	
}

function utf8ToGbk($str){
	$isNUM = false;
	if( is_numeric($str) && strlen($str) > 8 ){
		$isNUM = TRUE;
	}

	$str = mb_convert_encoding($str, 'GBK');
	
	if( $isNUM ){
		$str = "'".$str;
	}
	
	return $str;
}



